<template>
  <!-- 加载动画 -->
  <div v-if="isLoading" class="loading-container">
    <div class="spinner" />
    <p>数据处理中，请稍候...</p>
  </div>

  <!-- 数据内容 -->
  <div v-else class="dataDimenRedu">
    <div class="upchart" />
    <div class="downchart" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, defineExpose } from "vue";
import echarts from "@/plugins/echarts";
import { EffectScatterChart, ScatterChart } from "echarts/charts";
echarts.use([EffectScatterChart, ScatterChart]);
import { nextTick } from "vue";
import { codeFusion } from "@/api/dataProcessing";

const fileName = ref("default.json"); // 默认文件名
const c_way = ref(0);
const d_status = ref("未融合");
const chartYName = ref("");
const isLoading = ref(false); // 是否正在加载
const childStatusObj = ref({
  title: "未融合",
  status: 500
});

const emit = defineEmits(["childTitleStatusClick"]);
emit("childTitleStatusClick", childStatusObj.value);

const props = defineProps({
  selectValue: {
    type: Object,
    default() {
      return {};
    }
  },
  switchValue: {
    type: Array,
    default() {
      return [];
    }
  },
  fileData: {
    type: Object,
    default: null
  },
  fileName: {
    type: String,
    default: ""
  },
  currentDevice: {
    type: String,
    default: ""
  }
});

// 定义图表引用
const upChartRef = ref();
const downChartRef = ref();

// 定义图表数据
const upChartData = ref([
  { name: "卷曲伺服输出电流", data: [] },
  { name: "卷曲伺服输出电压", data: [] },
  { name: "送经伺服输出电流", data: [] },
  { name: "送经伺服输出电压", data: [] }
]);

const downChartData = ref([
  { name: "电压数据", data: [] },
  { name: "电流数据", data: [] }
]);

// 在 mounted 时获取图表
onMounted(() => {
  // 当 currentDevice 是 "整经机" 时，修改图表的图注

  renderUpChart();
  renderDownChart();
});

// 渲染上方图表
const renderUpChart = () => {
  const chartDom = document.querySelector(".upchart");
  if (!chartDom) {
    console.error("上方图表 DOM 未找到");
    return;
  }
  const myChart = echarts.init(chartDom);

  // 判断 currentDevice 是否是 "整经机"
  const isSprayWeavingMachine = props.currentDevice === "整经机";

  const option = {
    title: {
      text: props.currentDevice ? `${props.currentDevice} 数据融合前` : "",
      textStyle: {
        fontSize: 15
      }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c}"
    },
    legend: {
      data: upChartData.value.map(item => item.name),
      top: "10%"
    },
    xAxis: {
      type: "category",
      name: "样本点/个",
      nameTextStyle: {
        padding: [-7, 0, 0, 5],
        verticalAlign: "top",
        fontWeight: "bold", // 加粗
        color: "#000" // 黑色
      },
      nameGap: 30,
      axisLine: {
        lineStyle: {
          color: "#000", // 轴线颜色黑色
          width: 2 // 轴线宽度
        }
      }
      // axisLabel: {
      //   fontWeight: "bold", // 加粗
      //   color: "#000" // 黑色
      // }
    },
    yAxis: [
      {
        type: "value",
        name: isSprayWeavingMachine ? "圈数（条数）/圈（条）" : "电流/mA", // 判断是否是整经机
        position: "left",
        nameTextStyle: {
          fontWeight: "bold", // 加粗
          color: "#000" // 黑色
        },
        axisLabel: {
          formatter: isSprayWeavingMachine ? "{value} " : "{value} mA" // 根据条件显示单位
        }
      },
      {
        type: "value",
        name: isSprayWeavingMachine ? "长度/m" : "电压/V", // 判断是否是整经机
        position: "right",
        nameTextStyle: {
          fontWeight: "bold", // 加粗
          color: "#000" // 黑色
        },
        axisLabel: {
          formatter: isSprayWeavingMachine ? "{value} m" : "{value} V" // 根据条件显示单位
        }
      }
    ],
    series: upChartData.value.map((item, index) => ({
      name: item.name,
      type: "scatter",
      data: item.data,
      // 判断设备类型，并根据设备类型选择合适的 yAxisIndex
      yAxisIndex:
        props.currentDevice === "整经机"
          ? item.name.includes("数")
            ? 0
            : 1 // 当是"整经机"时，名称包含"数"的绑定到左轴，其他绑定到右轴
          : item.name.includes("电流")
            ? 0
            : 1 // 非"整经机"的默认逻辑
    }))
  };

  myChart.setOption(option, true);
};

// 渲染下方图表
const renderDownChart = () => {
  const chartDom = document.querySelector(".downchart");
  if (!chartDom) {
    console.error("下方图表 DOM 未找到");
    return;
  }
  const myChart = echarts.init(chartDom);

  // 判断 currentDevice 是否是 "整经机"
  const isSprayWeavingMachine = props.currentDevice === "整经机";

  const option = {
    title: {
      text: props.currentDevice ? `${props.currentDevice} 数据融合后` : "",
      textStyle: {
        fontSize: 15
      }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c}"
    },
    legend: {
      data: downChartData.value.map(item => item.name),
      top: "10%"
    },
    xAxis: {
      type: "category",
      name: "样本点/个",
      nameTextStyle: {
        padding: [-7, 0, 0, 5],
        verticalAlign: "top",
        fontWeight: "bold", // 加粗
        color: "#000" // 黑色
      },
      nameGap: 30,
      axisLine: {
        lineStyle: {
          color: "#000", // 轴线颜色黑色
          width: 2 // 轴线宽度
        }
      }
      // axisLabel: {
      //   fontWeight: "bold", // 加粗
      //   color: "#000" // 黑色
      // }
    },
    yAxis: [
      {
        type: "value",
        name: isSprayWeavingMachine ? "位移/m" : "电流/mA", // 判断是否是整经机
        position: "left",
        nameTextStyle: {
          fontWeight: "bold", // 加粗
          color: "#000" // 黑色
        },
        axisLabel: {
          formatter: isSprayWeavingMachine ? "{value} " : "{value} mA" // 根据条件显示单位
        }
      },
      {
        type: "value",
        name: isSprayWeavingMachine ? "长度/m" : "电压/V", // 判断是否是整经机
        position: "right",
        nameTextStyle: {
          fontWeight: "bold", // 加粗
          color: "#000" // 黑色
        },
        axisLabel: {
          formatter: isSprayWeavingMachine ? "{value} m" : "{value} V" // 根据条件显示单位
        }
      }
    ],
    series: downChartData.value.map((item, index) => ({
      name: item.name,
      type: "scatter",
      data: item.data,
      // 判断设备类型，并根据设备类型选择合适的 yAxisIndex
      yAxisIndex:
        props.currentDevice === "整经机"
          ? item.name.includes("位移")
            ? 0
            : 1 // 当是"整经机"时，名称包含"数"的绑定到左轴，其他绑定到右轴
          : item.name.includes("电流")
            ? 0
            : 1 // 非"整经机"的默认逻辑
    }))
  };

  myChart.setOption(option, true);
};

// 开始融合
const childMethod = () => {
  // 检查是否接收到文件
  if (!props.fileData) {
    childStatusObj.value.title = "未收到文件";
    childStatusObj.value.status = 400;
    emit("childTitleStatusClick", childStatusObj.value);
    return;
  }

  d_status.value = "融合中...";
  childStatusObj.value.title = "融合中....";
  isLoading.value = true; // 开始加载动画
  emit("childTitleStatusClick", childStatusObj.value);

  let formData = new FormData();
  formData.append("type", props.selectValue.selectC);
  formData.append("file", props.fileData);

  console.log("上传的文件:", props.fileData);

  if (props.switchValue[0]?.value) {
    formData.append("method", props.selectValue.selectA);
  }

  formData.append("strType", props.selectValue.selectC);
  if (props.currentDevice === "整经机") {
    // 修改 upChartData 的图注名称
    upChartData.value = [
      { name: "圈数", data: [] },
      { name: "带宽", data: [] },
      { name: "条数", data: [] },
      { name: "位移", data: [] }
    ];
    // 修改 downChartData 的图注名称
    downChartData.value = [
      { name: "位移", data: [] },
      { name: "带宽", data: [] }
    ];
  }
  codeFusion(formData)
    .then(res => {
      if (res.status === 200) {
        // 更新上方图表数据
        upChartData.value[0].data = res.data.curlingServoOutputCurrent || [];
        upChartData.value[1].data = res.data.curlingServoOutputVoltage || [];
        upChartData.value[2].data = res.data.sendingServoOutputCurrent || [];
        upChartData.value[3].data = res.data.sendingServoOutputVoltage || [];

        // upChartData.value[0].data = res.data.CurlingServoOutputCurrent || [];
        // upChartData.value[1].data = res.data.CurlingServoOutputVoltage || [];
        // upChartData.value[2].data = res.data.SendingServoOutputCurrent || [];
        // upChartData.value[3].data = res.data.SendingServoOutputVoltage || [];
        // 更新下方图表数据
        downChartData.value[0].data = res.data.oridata || [];
        downChartData.value[1].data = res.data.curlingServoOutputCurrent || [];

        // 切换状态，等待 DOM 渲染完成后再调用图表渲染
        isLoading.value = false;
        nextTick(() => {
          renderUpChart();
          renderDownChart();
        });

        if (res.data.oridata.length > 0) {
          childStatusObj.value.title = "融合完成";
          childStatusObj.value.status = res.status;
          d_status.value = "融合完成";
        }
      } else {
        childStatusObj.value.title = "融合失败";
        childStatusObj.value.status = res.status;
      }
    })
    .catch(error => {
      childStatusObj.value.title = "融合失败";
      childStatusObj.value.status = error.status || 500;
      console.log(error);
    })
    .finally(() => {
      emit("childTitleStatusClick", childStatusObj.value);
    });
};

defineExpose({
  childMethod
});

// 计算属性
const tagType = computed(() => {
  if (d_status.value === "未融合") {
    return "danger";
  } else if (d_status.value === "融合完成") {
    return "success";
  } else {
    return "warning";
  }
});
</script>

<style lang="scss" scoped>
.dataDimenRedu {
  .upchart {
    width: 100%;
    height: 260px;
  }

  .downchart {
    width: 100%;
    height: 260px;
  }
}
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(0, 0, 0, 0.1);
  border-top-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
